<?php

namespace App\V3\V3_2_7\Services;

use App\V3\V3_2_7\Models\AdminAddendumModel;
use App\V3\V3_2_7\Models\UploadImgModel;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use OSS\Core\OssException;
use OSS\Http\RequestCore_Exception;
use OSS\OssClient;

class UploadImgService
{
    /**
     *保存上传图片
     * Author: zlf
     * Created at 2024/6/17 13:53
     * @param $data
     * @return int
     */
    public static function saveImg($data): int
    {
        return UploadImgModel::query()->insertGetId($data);
    }

    /**
     *每日删除垃圾图片
     * Author: zlf
     * Created at 2024/6/17 13:53
     * @throws \Exception
     */
    public static function handleImg($data, $type)
    {
        $where = ["delete_flag" => 0];
        $clumnsArr = ["company_logo_img", "profile_photo_img"];
        //查询今日账户列表图片
        $adminImgArr = self::HendleImgSql("admin", $where, $clumnsArr, $data);
        $clumnsArr = ["materiel_img", "spec_img", "materiel_img_group"];
        //查询今日商品列表图片
        $goodsImgArr = self::HendleImgSql("materiel_type", $where, $clumnsArr, $data);
        $clumnsArr = ["proof_img", "audit_proof_img", "delivery_proof_img"];
        //查询今日申请单表列表图片
        $appliImgArr = self::HendleImgSql("application_form", $where, $clumnsArr, $data);
        //查询今日报溢报损列表图片
        $clumnsArr = ["proof_image"];
        $where = ["delete_flag" => 0, ["proof_image", "!=", ""]];
        $overflowImgArr = self::HendleImgSql("overflow_breakage", $where, $clumnsArr, $data);
        //查询今日销售列表图片
        $sellImgArr = self::HendleImgSql("sell", $where, $clumnsArr, $data);
        //查询今日采购列表图片
        $materielImgArr = self::HendleImgSql("materiel", $where, $clumnsArr, $data);
        //查询今日换货列表图片
        $barterImgArr = self::HendleImgSql("barter", $where, $clumnsArr, $data);
        //查询今日退货列表图片
        $returnImgArr = self::HendleImgSql("sales_return", $where, $clumnsArr, $data);
        //查询今日记账列表图片
        $tallyImgArr = self::HendleImgSql("tally", $where, $clumnsArr, $data);
        //查询今日上传的图片列表
        $clumnsArr = ["img_path"];
        $where = ["delete_flag" => 0, ["img_path", "!=", ""]];
        $uploadImgArr = self::HendleImgSql("upload_img", $where, $clumnsArr, $data);
        $clumnsArr = ["plate_image","id_card_image"];
        //查询今日销售单列表图片
        $sellDriverImgArr = self::HendleImgSql("sell_driver", [], $clumnsArr, $data);
        $imgArr = array_unique(
            array_filter(
                array_merge(
                    $adminImgArr, $goodsImgArr,
                    $appliImgArr, $overflowImgArr,
                    $returnImgArr, $tallyImgArr,
                    $sellDriverImgArr, $sellImgArr,
                )
            )
        );

        if (!empty($uploadImgArr) && !empty($imgArr)) {
            $ossClient = new OssClient(
                config("app.aliyun_oss_key"),
                config("app.aliyun_oss_secret"),
                config("app.aliyun_oss_endpoint")
            );
            foreach ($imgArr as $iVal) {
                if (File::exists(public_path($iVal))) {
                    $iPath = strstr($iVal, "uploads/");
                    try {
                        $ossClient->uploadFile(config('app.aliyun_oss_bucket'), $iPath, public_path($iVal));
                    } catch (OssException|RequestCore_Exception $e) {
                    }
                }
            }
            if ($type === 1) {
                $collection = collect($uploadImgArr);
                $diff = $collection->diff($imgArr);
                if (!empty($diff->all())) {
                    try {
                        foreach ($diff->all() as $dVal) {
                            $imgInfo = UploadImgModel::query()
                                ->where([
                                    "img_path" => $dVal,
                                    "delete_flag" => 0,
                                    "main_id" => $data["main_id"]
                                ])->first();
                            if (!empty($imgInfo)) {
                                $delPath = strstr($dVal, "uploads/");
                                $ossInfo = $ossClient->getObjectMeta(config("app.aliyun_oss_bucket"), $delPath);
                                $ossClient->deleteObject(config("app.aliyun_oss_bucket"), $delPath);
                                $imgInfo->delete_flag = 1;
                                $imgInfo->save();
                                AdminAddendumModel::query()->where(["main_id" => $data["main_id"]])
                                    ->decrement("file_total_size", $ossInfo["content-length"]);
                            }
                        }
                    } catch (OssException|RequestCore_Exception $e) {
                        return ['code' => 1, 'msg' => $e->getMessage()];
                    }
                }
            }
            if ($type === 2) {
                try {
                    $imgArr = array_unique(
                        array_filter(
                            array_merge(
                                $imgArr, $uploadImgArr,
                            )
                        )
                    );
                    foreach ($imgArr as $iVal) {
                        $delPath = strstr($iVal, "uploads/");
                        $ossClient->deleteObject(config("app.aliyun_oss_bucket"), $delPath);
                    }
                    AdminAddendumModel::query()
                        ->where(["main_id" => $data['main_id']])
                        ->update(["file_total_size" => 0]);
                    UploadImgModel::query()
                        ->where('main_id', $data['main_id'])
                        ->update(['delete_flag' => 1]);
                } catch (OssException|RequestCore_Exception $e) {
                    return ['code' => 1, 'msg' => $e->getMessage()];
                }
            }
        }
    }

    /**
     *查询所有图片表sql
     * Author: zlf
     * Created at 2024/6/17 11:16
     * @param $table
     * @param $where
     * @param array $columns
     * @return void
     */
    private static function HendleImgSql($table, $where, array $columns = ['*'], $data): array
    {
        $imgArr = [];
        DB::table($table)
            ->select($columns)
            ->where($where)
            ->where(function ($query) use ($data, $table) {
                if ($table === 'admin') {
                    $query->where('id', $data['main_id']);
                } else {
                    $query->where('main_id', $data['main_id']);
                }
            })->orderBy('created_at', 'asc')
            ->chunk(100, function (Collection $sellList) use (&$imgArr, $columns) {
                if (!empty($sellList->toArray())) {
                    $imgData = "";
                    foreach ($sellList as $list) {
                        foreach ($columns as $column) {
                            if (!empty($list->$column)) {
                                $imgData .= $list->$column . ",";
                            }
                        }
                    }
                    if (!empty($imgData)) {
                        $imgArr[] = array_unique(array_filter(explode(",", $imgData)));
                    }
                }
            });
        if (!empty($imgArr))
            $imgArr = array_unique(collect($imgArr)->flatten()->all());
        return $imgArr;
    }
}
